<?php

$topics = app::$db->grab( "SELECT `id`, `code` ,`title`, `card` FROM `topics` ORDER BY `ord` ASC", array(), 'code' );

if ( isset( $key[2] ) and isset( $topics[ $key[2] ] ) )
{
  $topic_id     = app::$db->get( "SELECT `id` FROM `topics` WHERE `code` = ?", array( $key[2] ), 'id' );

  $pending      = app::$db->grab( "SELECT `code`, `topic_id`, `voting_number`, `voting_title`, `title`, `team` FROM `requests` WHERE `topic_id` = ? AND status = 'pending'", array( $topic_id ) );
    
  $waiting      = app::$db->grab( "SELECT `code`, `topic_id`, `voting_number`, `voting_title`, `title`, `team` FROM `requests` WHERE `topic_id` = ? AND status = 'waiting'", array( $topic_id ) );
  $approved     = app::$db->grab( "SELECT `code`, `topic_id`, `voting_number`, `voting_title`, `title`, `team` FROM `requests` WHERE `topic_id` = ? AND status = 'approved'", array( $topic_id ) );
  $disapproved  = app::$db->grab( "SELECT `code`, `topic_id`, `voting_number`, `voting_title`, `title`, `team` FROM `requests` WHERE `topic_id` = ? AND status = 'disapproved'", array( $topic_id ) );

  require_once HTML . 'autumn/header.php';
  require_once HTML . 'autumn/cases/orgs/caves/requests/topic.php';
  require_once HTML . 'autumn/footer.php';    
}
else
{
  $stat = app::$db->grab("
    SELECT t.`code`, r.`status`, COUNT( r.`id` ) AS 'count'
    FROM `requests` r
    INNER JOIN `topics` t ON t.`id` = r.`topic_id`
    GROUP BY t.`code`, r.`status`
    ORDER BY t.`code`, r.`status`"  
  );
    
  require_once HTML . 'autumn/header.php';
  require_once HTML . 'autumn/cases/orgs/caves/requests/statistic.php';
  require_once HTML . 'autumn/footer.php';    
}

function Print_Request_Link($topics, $request) {

  foreach( $topics as $topic_check ) {
    if ($topic_check['id'] == $request['topic_id']) $topic = $topic_check;
  }
  
  $request_caption = $request['code'];
  if ($request['voting_number']) {
    $request_caption = $request_caption.' &nbsp; '.$topic['card'].$request['voting_number'].'. '.$request['voting_title'];
  } else if ($request['title']) {
    $request_caption = $request_caption.' &nbsp; '.$request['title'];
  }

  return "<a href='/requests/{$request['code']}/'>{$request_caption}</a>";

}

exit;